package com.ideaaedi.zoo.example.springboot.seata_dynamicds_sharding.beta.service;

import com.ideaaedi.commonspring.transaction.DefaultManualTransactionSupport;
import com.ideaaedi.zoo.diy.artifact.dynamic.datasource.datasource.DatasourceSwitcher;
import com.ideaaedi.zoo.example.springboot.seata_dynamicds_sharding.beta.po.StudentPO;
import com.ideaaedi.zoo.example.springboot.seata_dynamicds_sharding.beta.po.TeacherPO;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;

@Service
public class BizService {
    
    @Autowired
    BizService4Basic bizService4Basic;
    
    @Resource
    private BizShardingService shardingService;
    
    /**
     * 写入一些数据
     */
    public void addSomeBetaData() {
        int id = (int)System.currentTimeMillis() % 1000000;
        // 插入数据
        bizService4Basic.insertStudent(StudentPO.builder().id(id).name("Beta 夏洛").build()); // 数据库 mysql  db_one
    
        // 切换到指定的数据源下，执行逻辑
        DatasourceSwitcher.switchTo("oracleBeta").voidExec(() -> {
        
            // 因为是不同的数据源，所以需要新开一个spring事务
            DefaultManualTransactionSupport.create(TransactionDefinition.PROPAGATION_REQUIRES_NEW).voidExec(
                    () -> bizService4Basic.insertTeacher(TeacherPO.builder().id(id).name("Beta 蒋老师").build()) // 数据库 oracle  ROOT.teacher
            );
        });
    
        // 切换到指定的数据源下，执行逻辑
        DatasourceSwitcher.switchTo("shardingBeta").voidExec(() -> {
        
            // 因为是不同的数据源，所以需要新开一个spring事务
            DefaultManualTransactionSupport.create(TransactionDefinition.PROPAGATION_REQUIRES_NEW).voidExec(
                    () -> shardingService.insertSomeShardingData() // 数据库 mysql  demo
            );
        });
        
    }
}